#coding:utf-8
import wmi
import configparser
import os

# print objNicConfig.IPAddress
# print objNicConfig.IPSubnet
# print objNicConfig.DefaultIPGateway


def show_network():
    #显示可用的网络适配器

    wmiService = wmi.WMI()
    colNicConfigs = wmiService.Win32_NetworkAdapterConfiguration(IPEnabled=True)
    i = 0
    for objNicConfig in colNicConfigs:
        i += 1
        print (i, objNicConfig.Description.encode("cp936"))


def confirm_ip(networkDescription):
    #测试：显示修改后的IP

    wmiService = wmi.WMI()
    colNicConfigs = wmiService.Win32_NetworkAdapterConfiguration(IPEnabled=True)
    print(colNicConfigs[int(networkDescription)-1].IPAddress)
    print(colNicConfigs[int(networkDescription)-1].IPSubnet)
    print(colNicConfigs[int(networkDescription)-1].DefaultIPGateway)
    gateway = colNicConfigs[int(networkDescription)-1].DefaultIPGateway
    return gateway[0]


def read_ini(cityIni):
    #读取ini文件的配置信息

    config = configparser.ConfigParser()
    config.read('data.ini')

    networkConig = list()

    networkConig.append(config.get(cityIni, "ip"))            #获取ini文件中的值（string），然后转成list
    networkConig.append(config.get(cityIni, "mask"))
    networkConig.append(config.get(cityIni, "gateway"))
    #config.close()
    print (networkConig[0])
    print (networkConig[1])
    print (networkConig[2])

    return networkConig

def read_ini_destination(destination_ip_list):
    config = configparser.ConfigParser()
    config.read('data.ini')

    list_ip = []
    ip = config.items(destination_ip_list)
    for i in ip:
        list_ip.append(i[1])
    #print('日志',list_ip)
    return list_ip
pass

def modify_ip(networkDescription, ipConfig):
    wmiService = wmi.WMI()
    colNicConfigs = wmiService.Win32_NetworkAdapterConfiguration(IPEnabled=True)
    objNicConfig = colNicConfigs[int(networkDescription)-1]
    #print '正在设置', objNicConfig.Description.encode("cp936")
    print ('正在设置', objNicConfig.Description)

    ip = list()
    mask = list()
    gateway = list()
    ip.append(ipConfig[0])
    mask.append(ipConfig[1])
    gateway.append(ipConfig[2])

    objNicConfig.EnableStatic(IPAddress=ip, SubnetMask=mask)
    objNicConfig.SetGateways(DefaultIPGateway=gateway)

    print ('设置完成')

def get_route():
    command = 'route print'
    list_route = os.popen(command).readlines()  # 其得到的是字符串组成的列表，字符串由GBK编码本身组成，因此需使用GBK将其解码
    #print (list_route)
    for index in range(len(list_route)):

        if list_route[index] == '永久路由:\n':
            flag_start = index + 2
        if list_route[index] == 'IPv6 路由表\n':
            flag_end = index - 3
            break


    list_route_ip = []
    for int_i in range(flag_start, flag_end +1 ):
        list = list_route[int_i].split()
        list_route_ip.append(list[0])

    return list_route_ip
pass

def route_del(route_list):

    for i in route_list:
        if i == '0.0.0.0':                    #若删除0.0.0.0的永久路由，会导致网关配置丢失，因此这里跳过删除0.0.0.0
            continue
        command = 'route delete ' + i
        print (command)
        os.popen(command)
pass

def route_write(ip, gateway):
    '''
    :param ip: 字符串列表
    :param gateway:字符串
    :return:
    '''
    '''
    :param ip:
    :param gateway:
    :return:
    '''
    for i in ip:
        command = 'route add ' + i + ' mask 255.255.255.0 ' + gateway + ' -p'
        print (command)
        os.popen(command)

pass

if __name__ == '__main__':
    print("选择功能：")
    print("1、修改IP地址")
    print("2、刷新永久路由")
    choice = input('>')
    if choice == '1':
        print("选择要修改的网络适配器：")
        show_network()
        networkDescription = input('>')
        cityIni = input('选择配置：')
        ipConfig = read_ini(cityIni)
        modify_ip(networkDescription,ipConfig)
        confirm_ip(networkDescription)
    elif choice == '2':
        route_list = get_route()
        route_del(route_list)

        print("选择要修改的网络适配器：")
        show_network()
        networkDescription = input('>')
        gateway = confirm_ip(networkDescription)

        ip = read_ini_destination('destination_ip_list')

        route_write(ip, gateway)
